<?php

class Lokasi extends \Eloquent {    

    public function tamus(){
        return $this->hasMany('Lokasi');
    }    

    public function tipe()
    {
        return $this->belongsTo('Tipe');
    }

    public function pemilik()
    {
        return $this->belongsTo('Penduduk');
    }

    public function penduduks()
    {
        return $this->belongsToMany('Penduduk');
    }

    public function kipems()
    {
        return $this->hasMany('Kipem');
    }    

	// Add your validation rules here
	public static $rules = [
        'tipe_id'     => 'required',
        'nama'        => 'required',
        'alamat'      => 'required',
        'penduduk_id' => 'required'
	];    

	// Don't forget to fill this array
	protected $fillable = [
        'tipe_id',
        'nama',
        'alamat',
        'lat_lng',
        'zoom',
        'keterangan',
        'is_active',
        'user_id',
        'ref_id',
        'action',
        'penduduk_id'
    ];

    public function scopeActive($query) {
        return $query->where('is_active', '=', '1');
    }

    public function getLatLngAttribute($value)
    {
        return explode('|', $value);
    }    

    public static function boot()
    {
        parent::boot();

        static::creating(function($lokasi)
        {
            $lokasi->user_id = Auth::user()->id;
        });

        // Setup event bindings...
        static::updated(function($lokasi)
        {
            $lokasi_after = static::active()->where('ref_id', '=', $lokasi->ref_id)->first();
            // id : sebelum $lokasi->id
            // id sesudah : $lokasi_after->id            
            foreach ($lokasi->penduduks as $penduduks) {                
                $lokasi->penduduks()->updateExistingPivot($penduduks->pivot->penduduk_id, array('lokasi_id' => $lokasi_after->id), false);
            }                        
        });        
    }

}
